import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

import { BaseHttpService } from '@core/base/service/base-http.service';

import { Area } from '../model';

@Injectable({ providedIn: 'root' })
export class AreaService extends BaseHttpService<Area> {
  private baseUrl = '/system/v1/areas';

  protected createModel(o: any): Area {
    return new Area(o);
  }

  public save(parentId: string, area: Area): Observable<string> {
    const queryParams = { parentId: parentId };
    return this._save(this.baseUrl, area, queryParams);
  }

  public update(id: string, area: Area): Observable<any> {
    return this._save(`${this.baseUrl}/${id}`, area);
  }

  public remove(id: string): Observable<any> {
    return this._delete(`${this.baseUrl}/${id}`);
  }

  public getCodeNameMap(): Observable<Record<string, string>> {
    return this.http.get<Record<string, string>>(`${this.baseUrl}/code-name`);
  }

  public getTop(): Observable<Area[]> {
    const queryParams = { onlyTop: true };
    return this._getList(`${this.baseUrl}/list`, queryParams);
  }

  public getByCodes(codes: string[]): Observable<Area[]> {
    const queryParams = { codes: codes };
    return this._getList(`${this.baseUrl}/list`, queryParams);
  }

  public getChildren(id: string): Observable<Area[]> {
    return this._getList(`${this.baseUrl}/${id}/children`);
  }

  public getGrandchildren(id: string): Observable<Area[]> {
    return this._getList(`${this.baseUrl}/${id}/grandchildren`);
  }

  public getById(id: string): Observable<Area> {
    return this._getOne(`${this.baseUrl}/${id}`);
  }
}
